package com.qyoung.dao;

import java.sql.*;
import java.util.List;
import java.util.ResourceBundle;

public class BaseDao {
    //定义变量
    private Connection conn;
    private PreparedStatement pps;
    private ResultSet rs;
    private int result; //影响行数

    //数据库连接变量
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //静态代码块加载资源
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        /*//绑定数据源
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);*/
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    protected Connection getConnection(){
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //获取预状态通道
    protected PreparedStatement getPps(String sql){
        try {
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pps;
    }
    //绑定参数：以集合的形式将所有参数存储
    protected void boundParam(List params){
        if (params!=null && params.size()>0){
            for (int i = 0; i < params.size(); i++) {
                try {
                    pps.setObject(i+1,params.get(i));
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //增删改操作：返回影响行数
    protected int update(String sql,List params){
        getPps(sql);
        boundParam(params);
        try {
            result = pps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
    //查询操作：返回结果集
    protected ResultSet query(String sql,List params){
        getPps(sql);
        boundParam(params);
        try {
            rs = pps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    //关闭所有资源
    protected void closeAll(){
        try {
            if (rs != null) {
                rs.close();
            }
            if (pps != null) {
                pps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
